import { Session } from '@utility/storage.js'
import { getUserInfoApi } from '@api/api.js'
const user = {
  namespaced: true,
  state: () => ({
    userInfo: {},
  }),
  getters: {
    getUserInfo: state => state.userInfo,
  },
  mutations: {
    USER_INFO(state, info) {
      state.userInfo = info
    },
    CLEAR_USER_INFO(state) {
      localStorage.clear()
      Session.clear()
      state.userInfo = {}
      state.userRegions = null
      state.defaultShowCity = null
    },
  },
  actions: {
    clearUserInfo({ commit }) {
      commit('CLEAR_USER_INFO')
    },
    setUserInfos({ commit, getters }) {
      return new Promise((resolve, reject) => {
        if (JSON.stringify(getters.getUserInfo) === '{}') {
          getUserInfoApi()
            .then(res => {
              if (res.code === 0) {
                commit('USER_INFO', res.data)
                const { userId, tenantId } = res.data.sysUser
                Session.set('tenantId', tenantId)
                localStorage.setItem('userId', userId)
                localStorage.setItem('tenantId', tenantId)

                resolve(res.data)
              }
            })
            .catch(reject)
        }
      })
    },
  },
}
export default user
